// 导入需要的模块
require('dotenv').config();
const { Client } = require('pg');

// 创建数据库连接
const client = new Client({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE
});

async function main() {
  try {
    await client.connect();
    console.log('数据库连接成功');
    
    // 查询系统管理员角色
    const adminRole = await client.query(`
      SELECT * FROM roles WHERE name = '系统管理员'
    `);
    
    if (adminRole.rows.length === 0) {
      console.log('未找到系统管理员角色');
      return;
    }
    
    const adminRoleId = adminRole.rows[0].id;
    console.log(`系统管理员角色ID: ${adminRoleId}`);
    
    // 查询关键权限
    const permissionCodes = [
      'system:permission:create',
      'system:permission:read',
      'system:permission:update',
      'system:permission:delete'
    ];
    
    // 检查这些权限是否存在
    const permissions = await client.query(`
      SELECT * FROM permissions WHERE code IN ($1, $2, $3, $4)
    `, permissionCodes);
    
    console.log('关键权限存在情况:');
    permissionCodes.forEach(code => {
      const found = permissions.rows.find(p => p.code === code);
      console.log(`- ${code}: ${found ? '存在' : '不存在'}`);
      if (found) {
        console.log(`  ID: ${found.id}`);
      }
    });
    
    // 检查系统管理员是否拥有这些权限
    if (permissions.rows.length > 0) {
      const permissionIds = permissions.rows.map(p => p.id);
      
      const rolePermissions = await client.query(`
        SELECT permission_id FROM role_permissions 
        WHERE role_id = $1 AND permission_id IN ($2, $3, $4, $5)
      `, [adminRoleId, ...permissionIds]);
      
      console.log('\n系统管理员拥有的关键权限:');
      permissions.rows.forEach(perm => {
        const hasPermission = rolePermissions.rows.some(rp => rp.permission_id === perm.id);
        console.log(`- ${perm.code}: ${hasPermission ? '拥有' : '未拥有'}`);
      });
    }
    
    // 检查权限与角色的关联表
    const rolePermissionsCount = await client.query(`
      SELECT COUNT(*) FROM role_permissions 
      WHERE role_id = $1
    `, [adminRoleId]);
    
    console.log(`\n系统管理员角色关联的权限数量: ${rolePermissionsCount.rows[0].count}`);
    
    // 检查系统用户和管理员角色关联情况
    const adminUser = await client.query(`
      SELECT * FROM users WHERE username = 'admin'
    `);
    
    if (adminUser.rows.length > 0) {
      const adminUserId = adminUser.rows[0].id;
      console.log(`\n管理员用户ID: ${adminUserId}`);
      
      const userRoles = await client.query(`
        SELECT * FROM user_roles 
        WHERE user_id = $1 AND role_id = $2
      `, [adminUserId, adminRoleId]);
      
      if (userRoles.rows.length > 0) {
        console.log('管理员用户已关联系统管理员角色');
      } else {
        console.log('警告: 管理员用户未关联系统管理员角色');
      }
    } else {
      console.log('未找到管理员用户');
    }
    
  } catch (error) {
    console.error('查询出错:', error);
  } finally {
    await client.end();
    console.log('数据库连接已关闭');
  }
}

main(); 